<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['user_id', 'username', 'email'] as $value) {
        if (!isset($_POST[$value])) {
            throw new Exception(fieldMap($value) . '为必传项');
        }

        if (empty($_POST[$value])) {
            throw new Exception(fieldMap($value) . '不能为空');
        }

        if ($value === 'username' && strlen($_POST['username']) < 2) {
            throw new Exception('用户名长度不能小于2位');
        }
    }

    // 判断用户是否存在
    $sql = 'select * from users where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['user_id']]);
    if (empty($stmt->fetch(PDO::FETCH_ASSOC))) {
        throw new Exception('用户不存在，无法修改');
    }

    // 更新用户信息
    $sql = 'update users set username = ?, email = ? where id = ?';
    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute([$_POST['username'], $_POST['email'], $_POST['user_id']]);
    if (empty($res)) {
        throw new Exception('更新失败');
    }

    myResponse('', 1, 200);
} catch (Exception $e) {
    myResponse($e->getMessage(), 0, 200);
}
